# -*- coding=utf-8 -*-
# Created Time: 2016年08月23日 星期二 16时06分59秒
# File Name: encrypt.py

"""
密码 加密/验证
"""

import os
import hashlib
from hashlib import sha256
from hmac import HMAC

def encrypt_password(password, salt=None):
    """ """

    sh = hashlib.sha256()
    sh.update(password+salt)
    return sh.hexdigest()

def encrypt_password_bak(password, salt=None):
    """Hash password on the fly."""

    if salt is None:
        salt = os.urandom(8) # 64 bits.

    assert 8 == len(salt)
    assert isinstance(salt, str)

    if isinstance(password, unicode):
        password = password.encode('UTF-8')

    assert isinstance(password, str)

    result = password
    for i in xrange(10):
        result = HMAC(result, salt, sha256).digest()

    return salt + result


def validate_password(hashed, input_password, salt):

	return hashed == encrypt_password(input_password, salt)

def main():

	hashed = encrypt_password('idealsee02', '55c808909tigered22388bbb')

	print 'hashed: ', hashed

	assert validate_password(hashed, 'tiger')

if __name__ == '__main__':
	main()
